<?php

namespace app\api\controller;

use app\services\QuestionStoreService;
use support\Db;
use support\Request;

class QuestionController
{
    public static function categories(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $length = $request->post('length', 10);

            $data = QuestionStoreService::categoryList($page, $length);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }
    public static function list(Request $request)
    {
        Db::beginTransaction();
        try {
            $categoryId = $request->post('category_id', 1);
            $length = $request->post('length', 10);

            [$examId, $data] = QuestionStoreService::list($categoryId, $length);

            Db::commit();
            return ok_rsp('成功', ['exam_id' => $examId, 'list' => $data]);
        } catch (\Exception $e) {
            Db::rollBack();
            return e_rsp($e);
        }
    }

    public static function submit(Request $request)
    {
        try {
            $examId = $request->post('exam_id', 0);
            $answers = $request->post('answers');

            $data = QuestionStoreService::submit($examId, $answers);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

    public static function rankList(Request $request)
    {
        try {
            $categoryId = $request->post('category_id', 1);
            [$data, $rank] = QuestionStoreService::rankList($categoryId);
            return ok_rsp('成功', ['list' => $data, 'rank' => $rank]);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }
}